﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using DSAClient.Models.Input;

namespace DSAClient.Core
{
    public class ImageHelper
    {
        public delegate object QiniuUploadTaskDele(object stat);
        private const int AreaWidth = 299;       //pictureBox控件的最大宽度
        private const int AreaHeight = 201;     //pictureBox控件的最大高度

        /*
         * 图片裁剪方法
         * param b:需裁剪的图片位图
         * param StartX：裁剪起始X坐标
         * param StartY：裁剪起始Y坐标
         * param iWidth：裁剪宽度
         * param iHeight：裁剪高度
         * */
        public static Bitmap KiCut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
        {
            if (b == null)
            {
                return null;
            }

            int w = b.Width;
            int h = b.Height;
            if (StartX >= w || StartY >= h)
            {
                return null;
            }

            if (StartX + iWidth > w)
            {
                iWidth = w - StartX;
            }

            if (StartY + iHeight > h)
            {
                iHeight = h - StartY;
            }
            try
            {
                Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(bmpOut);
                g.Clear(Color.White);
                g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
                g.Dispose();
                return bmpOut;
            }
            catch
            {
                return null;
            }
        }

        public static bool KiCut(Image b, string dFile, int StartX, int StartY, int iWidth, int iHeight)
        {
            if (b == null)
            {
                return false;
            }

            int w = b.Width;
            int h = b.Height;
            if (StartX >= w || StartY >= h)
            {
                return false;
            }

            if (StartX + iWidth > w)
            {
                iWidth = w - StartX;
                //StartX = 0;
            }
            //else
            //    StartX = 0;

            if (StartY + iHeight > h)
            {
                iHeight = h - StartY;
            }
            //else
            //    StartY = 0;
            try
            {
                return GetPicThumbnail(b, dFile, StartX, StartY, iHeight, iWidth, 70);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth"></param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <returns></returns>
        public static bool GetPicThumbnail(Image iSource, string dFile, int StartX, int StartY, int dHeight, int dWidth, int flag)
        {

            //System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }
            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);
            g.Clear(Color.White);

            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle(0, 0, dWidth, dHeight), new Rectangle(StartX, StartY, dWidth, dHeight), GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }

        /// <summary>
        /// 毫米转象数
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static double MillimetersToPixelsWidth(float length)
        {
            //System.Windows.Forms.Panel p = new System.Windows.Forms.Panel();
            //System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle);

            //IntPtr hdc = g.GetHdc();
            //int width = GetDeviceCaps(hdc, 4);     // HORZRES 
            //int pixels = GetDeviceCaps(hdc, 8);     // BITSPIXEL
            //g.ReleaseHdc(hdc);

            //return (((double)pixels / (double)width) * (double)length);
            return length * 3.78;
        }

        [DllImport("gdi32.dll")]
        private static extern int GetDeviceCaps(IntPtr hdc, int Index);

        private static Size GetImgSize(Image img, PailideConfig config)
        {
            Size size = new Size();
            //计算正常比例
            if (img.Width / config.ImgWidth > img.Height / config.ImgHeight)//宽度为正常缩放宽度
            {
                size.Height = (int)(img.Width * config.ImgHeight / config.ImgWidth);
                size.Width = img.Width;
            }
            else//高度为正常缩放高度
            {
                size.Height = img.Height;
                size.Width = (int)(img.Height * config.ImgWidth / config.ImgHeight); ;
            }
            return size;
        }

        public static int ParseImgNum(PailideConfig config, List<ImageInfo> maps)
        {
            int result = 0;
            if (config.IsMerger)
            {
                foreach (ImageInfo m in maps)
                {
                    if (m != null && m.ImgPath != "")
                    {
                        for (int i = 0; i < m.ImgNum; i++)
                        {
                            result++;
                        }
                    }
                }
                result = (int)Math.Ceiling((double)(result / 2f));
            }
            else
            {
                foreach (ImageInfo m in maps)
                {
                    if (m != null && m.ImgPath != null)
                    {
                        result++;
                    }
                }
            }
            return result;
        }

        #region 合并图片
        /// <summary>
        /// 合并图片
        /// </summary>
        /// <param name="maps"></param>
        /// <returns></returns>
        public static void MergerImg(PailideConfig config, List<ImageInfo> maps, string oid, ImageForm form)
        {
            List<ImageInfo> tempmaps = new List<ImageInfo>();
            if (config.IsMerger)
            {
                foreach (ImageInfo m in maps)
                {
                    if (m != null && m.ImgPath != null)
                    {
                        for (int i = 0; i < m.ImgNum; i++)
                        {
                            ImageInfo temp = (ImageInfo)m.Clone();
                            temp.ImgNum = 1;
                            tempmaps.Add(temp);
                        }
                    }
                }
            }
            else
            {
                foreach (ImageInfo m in maps)
                {
                    if (m != null && m.ImgPath != null)
                    {
                        //for (int i = 0; i < m.ImgNum; i++)
                        //{
                        tempmaps.Add((ImageInfo)m.Clone());
                        //}
                    }
                }
            }

            int picCount = 0;
            if (maps.Count == 0)
                throw new Exception("图片数不能够为0");
            if (config.IsMerger)
                picCount = (int)Math.Ceiling((double)(tempmaps.Count / 2f));
            else
                picCount = maps.Count;

            int imgWidth = 0;
            int imgHeight = 0;

            for (int j = 0; j < picCount; j++)
            {
                string filename = Guid.NewGuid().ToString().Replace("-", "") + ".jpg";
                string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\ImgTemplate\\" + filename;
                if (config.IsMerger)
                {
                    Image img1 = null;
                    if (!tempmaps[j * 2].IsCut)
                    {
                        //tempmaps[j * 2].PicSize = new Size((int)config.ImgHeight, (int)config.ImgWidth);
                        tempmaps[j * 2].PicSize = new Size((int)config.ImgWidth, (int)config.ImgHeight);
                        //img1 = CreateBigPic(tempmaps[j * 2].Img, tempmaps[j * 2].PicSize);

                        Image img = Image.FromFile(tempmaps[j * 2].ImgPath);
                        AdjustmentImgRotation(img, (int)config.ImgWidth, (int)config.ImgHeight, tempmaps[j * 2]);
                        //img1 = CreateBigPic(tempmaps[j * 2].Img, new Size((int)config.ImgWidth, (int)config.ImgHeight));
                        img1 = CreateBigPic(img, new Size((int)config.ImgWidth, (int)config.ImgHeight));
                        //img1.Save(@"G:\订阅号\big\" + Guid.NewGuid().ToString());
                        tempmaps[j * 2].Rect = new Rectangle(new Point(0, 0), tempmaps[j * 2].PicSize);
                    }
                    else
                    {
                        Image img = Image.FromFile(tempmaps[j * 2].ImgPath);
                        AdjustmentImgRotation(img, (int)config.ImgWidth, (int)config.ImgHeight, tempmaps[j * 2]);
                        img1 = img;
                    }
                    Bitmap map = ImageHelper.KiCut((Bitmap)img1,
                                tempmaps[j * 2].Rect.X * img1.Width / tempmaps[j * 2].PicSize.Width,
                                tempmaps[j * 2].Rect.Y * img1.Height / tempmaps[j * 2].PicSize.Height,
                                img1.Width * tempmaps[j * 2].Rect.Width / tempmaps[j * 2].PicSize.Width,
                                img1.Height * tempmaps[j * 2].Rect.Height / tempmaps[j * 2].PicSize.Height);  //通过比例换算裁剪图片保证裁剪结果的正确
                    img1.Dispose();
                    Bitmap map2 = null;
                    Image img2 = null;
                    if ((j + 1) * 2 - 1 < tempmaps.Count)
                    {
                        if (!tempmaps[(j + 1) * 2 - 1].IsCut)
                        {
                            //tempmaps[(j + 1) * 2 - 1].PicSize = new Size((int)config.ImgHeight, (int)config.ImgWidth);
                            tempmaps[(j + 1) * 2 - 1].PicSize = new Size((int)config.ImgHeight, (int)config.ImgWidth);
                            //img2 = CreateBigPic(tempmaps[(j + 1) * 2 - 1].Img, tempmaps[(j + 1) * 2 - 1].PicSize);
                            Image img = Image.FromFile(tempmaps[(j + 1) * 2 - 1].ImgPath);
                            AdjustmentImgRotation(img, (int)config.ImgWidth, (int)config.ImgHeight, tempmaps[(j + 1) * 2 - 1]);

                            img2 = CreateBigPic(img, new Size((int)config.ImgWidth, (int)config.ImgHeight));
                            //img2.Save(@"G:\订阅号\big\" + Guid.NewGuid().ToString());
                            tempmaps[(j + 1) * 2 - 1].Rect = new Rectangle(new Point(0, 0), tempmaps[(j + 1) * 2 - 1].PicSize);
                        }
                        else
                        {
                            Image img = Image.FromFile(tempmaps[(j + 1) * 2 - 1].ImgPath);
                            AdjustmentImgRotation(img, (int)config.ImgWidth, (int)config.ImgHeight, tempmaps[(j + 1) * 2 - 1]);

                            img2 = img;// tempmaps[(j + 1) * 2 - 1].Img;
                        }

                        map2 = ImageHelper.KiCut((Bitmap)img2,
                                tempmaps[(j + 1) * 2 - 1].Rect.X * img2.Width / tempmaps[(j + 1) * 2 - 1].PicSize.Width,
                                tempmaps[(j + 1) * 2 - 1].Rect.Y * img2.Height / tempmaps[(j + 1) * 2 - 1].PicSize.Height,
                                img2.Width * tempmaps[(j + 1) * 2 - 1].Rect.Width / tempmaps[(j + 1) * 2 - 1].PicSize.Width,
                                img2.Height * tempmaps[(j + 1) * 2 - 1].Rect.Height / tempmaps[(j + 1) * 2 - 1].PicSize.Height);  //通过比例换算裁剪图片保证裁剪结果的正确
                        img2.Dispose();

                        if (map.Width > map2.Width)
                        {
                            imgWidth = map2.Width;
                            imgHeight = map2.Height;
                        }
                        else
                        {
                            imgWidth = map.Width;
                            imgHeight = map.Height;
                        }
                    }
                    else
                    {
                        imgWidth = map.Width;
                        imgHeight = map.Height;
                    }

                    int sbk = (int)((config.UpFrame) * imgWidth / config.ImgWidth);
                    int dbk = (int)((config.DownFrame) * imgWidth / config.ImgWidth);
                    int cbk = (int)((config.RightFrame) * imgWidth / config.ImgWidth);

                    int leftbk = (int)((config.LeftFrame) * imgWidth / config.ImgWidth);
                    int rightbk = (int)((config.RightFrame) * imgWidth / config.ImgWidth);
                    int upbk = (int)((config.UpFrame) * imgHeight / config.ImgHeight);
                    int downbk = (int)((config.DownFrame) * imgHeight / config.ImgHeight);
                    Bitmap backgroudImg = null;
                    //创建要显示的图片对象,根据参数的个数设置宽度
                    if (config.PictureType == "拍立得")
                        backgroudImg = new Bitmap(leftbk + imgWidth + rightbk, 2 * upbk + 2 * downbk + imgHeight * 2, PixelFormat.Format24bppRgb);
                    else
                        backgroudImg = new Bitmap(imgWidth, 2 * (downbk + imgHeight), PixelFormat.Format24bppRgb);
                    Graphics g = Graphics.FromImage(backgroudImg);
                    //清除画布,背景设置为白色
                    g.Clear(System.Drawing.Color.White);
                    g.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高，即消除锯齿
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    if (config.PictureType == "拍立得")
                        //插入第一张图片
                        g.DrawImage(map, leftbk, upbk, imgWidth, imgHeight);
                    else
                        g.DrawImage(map, 0, 0, imgWidth, imgHeight);
                    if ((j + 1) * 2 - 1 < tempmaps.Count)
                    {
                        //插入第二张图片
                        if (map2 != null)
                        {
                            if (config.PictureType == "拍立得")
                            {
                                //g.DrawImage(map2, dbk, 2 * sbk + dbk + imgHeight, imgWidth, imgHeight);
                                g.DrawImage(map2, leftbk, 2 * upbk + imgHeight + downbk, imgWidth, imgHeight);
                            }
                            else
                                g.DrawImage(map2, 0, downbk * 2 + imgHeight, imgWidth, imgHeight);
                        }
                    }
                    backgroudImg.Save(filepath, ImageFormat.Jpeg);

                    g.Dispose();
                    backgroudImg.Dispose();
                    map.Dispose();
                    if (map2 != null)
                        map2.Dispose();
                }
                else
                {
                    Image img1 = null;
                    if (!maps[j].IsCut)
                    {
                        maps[j].PicSize = new Size((int)config.ImgWidth, (int)config.ImgHeight);
                        //img1 = CreateBigPic(maps[j].Img, maps[j].PicSize);
                        Image img = Image.FromFile(maps[j].ImgPath);
                        AdjustmentImgRotation(img, (int)config.ImgWidth, (int)config.ImgHeight, maps[j]);

                        img1 = CreateBigPic(img, new Size((int)config.ImgWidth, (int)config.ImgHeight));
                        //img1.Save(@"G:\订阅号\big\" + Guid.NewGuid().ToString());
                        maps[j].Rect = new Rectangle(new Point(0, 0), maps[j].PicSize);
                    }
                    else
                    {
                        Image img = Image.FromFile(maps[j].ImgPath);
                        AdjustmentImgRotation(img, (int)config.ImgWidth, (int)config.ImgHeight, maps[j]);
                        img1 = img;// maps[j].Img;
                    }

                    Bitmap map = KiCut((Bitmap)img1, maps[j].Rect.X * img1.Width / maps[j].PicSize.Width, maps[j].Rect.Y * img1.Height / maps[j].PicSize.Height,
                         img1.Width * maps[j].Rect.Width / maps[j].PicSize.Width, img1.Height * maps[j].Rect.Height / maps[j].PicSize.Height);  //裁剪照片,然后合并图片
                    img1.Dispose();
                    imgWidth = map.Width;
                    imgHeight = map.Height;

                    int sbk = (int)((config.UpFrame) * imgWidth / config.ImgWidth);
                    int dbk = (int)((config.DownFrame) * imgWidth / config.ImgWidth);
                    int cbk = (int)((config.RightFrame) * imgWidth / config.ImgWidth);

                    int leftbk = (int)((config.LeftFrame) * imgWidth / config.ImgWidth);
                    int rightbk = (int)((config.RightFrame) * imgWidth / config.ImgWidth);
                    int upbk = (int)((config.UpFrame) * imgHeight / config.ImgHeight);
                    int downbk = (int)((config.DownFrame) * imgHeight / config.ImgHeight);

                    //创建要显示的图片对象,根据参数的个数设置宽度
                    Bitmap backgroudImg = new Bitmap(leftbk + imgWidth + rightbk, upbk + downbk + imgHeight, PixelFormat.Format24bppRgb);

                    Graphics g = Graphics.FromImage(backgroudImg);
                    //清除画布,背景设置为白色
                    g.Clear(System.Drawing.Color.White);
                    g.SmoothingMode = SmoothingMode.AntiAlias;  //使绘图质量最高，即消除锯齿
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.CompositingQuality = CompositingQuality.HighQuality;

                    g.DrawImage(map, leftbk, upbk, imgWidth, imgHeight);

                    backgroudImg.Save(filepath, ImageFormat.Jpeg);
                    g.Dispose();
                    backgroudImg.Dispose();
                    map.Dispose();
                }
                //上传图片到七牛空间
                new QiniuUploadTask(filepath, tempmaps[j], oid).Run(null);
                form.p.Invoke((MethodInvoker)delegate
                 {
                     //form.p.Text = "正在上传文件" + filename + "。请耐心等待！！";
                     form.p.Value++;
                     form.p.Text = "已经上传" + ((float)(form.p.Value) / (float)(form.p.Maximum)) * 100 + "%,请耐心等待！！";
                     Application.DoEvents();
                 });
            }

            //return backgroudImg;
        }
        #endregion

        #region 合并图片
        /// <summary>
        /// 合并图片
        /// </summary>
        /// <param name="bitMapDic"></param>
        /// <returns></returns>
        private static Bitmap MergerImg(Dictionary<string, Bitmap> bitMapDic)
        {
            if (bitMapDic == null || bitMapDic.Count == 0)
                throw new Exception("图片数不能够为0");
            //创建要显示的图片对象,根据参数的个数设置宽度
            Bitmap backgroudImg = new Bitmap(bitMapDic.Count * 12, 16);
            Graphics g = Graphics.FromImage(backgroudImg);
            //清除画布,背景设置为白色
            g.Clear(System.Drawing.Color.White);
            int j = 0;
            foreach (KeyValuePair<string, Bitmap> entry in bitMapDic)
            {
                Bitmap map = entry.Value;
                g.DrawImage(map, j * 11, 0, map.Width, map.Height);
                j++;
            }
            g.Dispose();
            return backgroudImg;
        }
        #endregion

        public static Bitmap CreateBigPic(Image img, Size picSize)
        {
            Size size = GetImgSize(img, picSize);
            Bitmap ob = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(ob))
            {

                //Graphics g = Graphics.FromImage(ob);
                g.Clear(Color.White);
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(img, (size.Width - img.Width) / 2, (size.Height - img.Height) / 2, img.Width, img.Height);// new Rectangle(0, 0, dWidth, dHeight), new Rectangle(StartX, StartY, dWidth, dHeight), GraphicsUnit.Pixel);
                //ob.Save(@"G:\订阅号\big\" + Guid.NewGuid().ToString()+".jpg");
                g.Dispose();
                img.Dispose();
            }
            //ob.Save(@"G:\订阅号\big\" + Guid.NewGuid().ToString() + ".jpg");
            return ob;
        }

        public static Size GetImgSize(Image img, Size s)
        {
            Size size = new Size();
            //计算正常比例
            if (img.Width / s.Width >= img.Height / s.Height)//宽度为正常缩放宽度
            {
                size.Height = (int)(img.Width * s.Height / s.Width);
                size.Width = img.Width;
            }
            else//高度为正常缩放高度
            {
                size.Height = img.Height;
                size.Width = (int)(img.Height * s.Width / s.Height); ;
            }
            return size;
        }

        public static Bitmap CreateBigPic(Image img)
        {
            Size size = GetImgSize(img);
            Bitmap ob = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(ob))
            {

                //Graphics g = Graphics.FromImage(ob);
                g.Clear(Color.White);
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(img, (size.Width - img.Width) / 2, (size.Height - img.Height) / 2, img.Width, img.Height);// new Rectangle(0, 0, dWidth, dHeight), new Rectangle(StartX, StartY, dWidth, dHeight), GraphicsUnit.Pixel);
                g.Dispose();
                img.Dispose();
            }
            //ob.Save(@"G:\订阅号\big\" + Guid.NewGuid().ToString() + ".jpg");
            return ob;
        }

        public static Size GetImgSize(Image img)
        {
            Size size = new Size();
            //计算正常比例
            if (img.Width / AreaWidth > img.Height / AreaHeight)//宽度为正常缩放宽度
            {
                size.Height = (int)(img.Width * AreaHeight / AreaWidth);
                size.Width = img.Width;
            }
            else//高度为正常缩放高度
            {
                size.Height = img.Height;
                size.Width = (int)(img.Height * AreaWidth / AreaHeight); ;
            }
            return size;
        }

        /// <summary>
        /// 调整图片旋转，实现最少留白
        /// </summary>
        /// <param name="imageList"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        protected static void AdjustmentImgRotation(Image image, float w, float h, ImageInfo imageInfo)
        {
            if (image.Width / image.Height < h / w)
            {
                image.RotateFlip(RotateFlipType.Rotate270FlipNone);
            }
            Size size = ParsePictureBoxSize(image, AreaWidth, AreaHeight);
            imageInfo.PicSize = size;
            if (size.Width / w <= size.Height / h)//<=
            {
                int width = size.Width;
                int height = (int)(h * size.Width / w);
                if (imageInfo.Rect.Width == 0 && imageInfo.Rect.Height == 0)
                    imageInfo.Rect = new Rectangle((size.Width - width) / 2, (size.Height - height) / 2, width, height);
            }
            else
            {
                int width = (int)(w * size.Height / h);
                int height = size.Height;
                if (imageInfo.Rect.Width == 0 && imageInfo.Rect.Height == 0)
                    imageInfo.Rect = new Rectangle((size.Width - width) / 2, (size.Height - height) / 2, width, height);
            }
        }

        /// <summary>
        /// 计算图片框的大小和位置
        /// </summary>
        /// <param name="img"></param>
        /// <param name="pb"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="panelSize"></param>
        public static Size ParsePictureBoxSize(Image img, int width, int height)
        {
            Size size = new Size();
            if ((float)img.Width / (float)img.Height < (float)width / (float)height)
            {
                size.Height = height;
                size.Width = img.Width * height / img.Height;
            }
            else
            {
                size.Width = width;
                size.Height = img.Height * width / img.Width;
            }
            return size;
        }
    }
}
